package main

import (
	"deploy-tools/config"
	"deploy-tools/executor"
	"deploy-tools/model"
	"deploy-tools/remote"
	"deploy-tools/utils"
	"flag"
	"fmt"
	"log"
	"path/filepath"
)

func main() {
	c := flag.String("c", "", "config path")
	cmd := flag.String("cmd", "", "execute command")
	src := flag.String("src", "", "copy filename or filepath")
	dst := flag.String("dst", "", "copy dst")
	h := flag.String("h", "", "host name")
	jobs := flag.Bool("jobs", false, "run jobs")
	jobFile := flag.String("jobfile", "", "job file")
	job := flag.String("job", "", "job name")
	fetch := flag.Bool("fetch", false, "fetch mode")
	encrypt := flag.String("encrypt", "", "encrypt text")
	key := flag.String("key", "", "encrypt key")
	reset := flag.Bool("reset", false, "reset mode")
	flag.Parse()

	dir, err := filepath.Abs("./")
	if err != nil {
		panic(err)
		return
	}
	log.Printf("current: %s", dir)

	configPath := *c
	host := *h
	fmt.Printf("\n")

	if configPath == "" {
		configPath, err = filepath.Abs("./config.local.yaml")
		if err != nil {
			panic(err)
		}
		if utils.IsExist(configPath) {
			configPath = "config.local.yaml"
		} else {
			configPath, _ = filepath.Abs("./config.yaml")
		}
	}
	if !utils.IsExist(configPath) {
		panic("please input config.yaml, current dir or -c xxx")
	}
	err = config.LoadConfig(configPath)
	if err != nil {
		panic(err)
	}
	err = config.LoadJobs(*jobFile)
	if err != nil {
		panic(err)
	}
	if *key != "" {
		config.GlobalConfig.EncryptKey = *key
	}
	if *encrypt != "" {
		res, err := utils.Encrypt(*encrypt, config.GlobalConfig.EncryptKey)
		if err != nil {
			panic(err)
		}
		log.Printf("ENC(%s)", res)
		return
	}
	err = config.DecryptConfig()
	if err != nil {
		panic(err)
	}

	exec := executor.NewExecutor()
	if *reset {
		exec.Recorder.ClearAll()
		config.VarsCache.ClearAll()
	}
	if *jobs || *cmd == "" {
		exec.Execute(*job)
		return
	}
	task := model.Task{
		Name:      "temp",
		Src:       *src,
		Dst:       *dst,
		Command:   *cmd,
		Fetch:     *fetch,
		AllowFail: false,
	}

	if host == "" {
		panic("please input host name")
	}
	remoteHost := config.HostMap[host]
	if remoteHost == nil {
		panic("please config host info in config.yaml")
	}

	client := remote.NewRemote(remoteHost)
	err = client.Connect(10)
	if err != nil {
		panic(err)
	}
	res, err := exec.ExecuteTask("temp", &task, client)
	if err != nil {
		panic(err)
	}
	log.Printf("execute result: %s", res)
}
